import React, { useState, useEffect } from 'react';

const Carousel = () => {
  const [currentSlide, setCurrentSlide] = useState(0);
  const totalSlides = slides.length;

  // 自动播放逻辑
  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % totalSlides);
    }, 3000);

    return () => clearInterval(interval); // 清理定时器
  }, [totalSlides]);

  // 切换上一张
  const prevSlide = () => {
    setCurrentSlide((prev) => (prev - 1 + totalSlides) % totalSlides);
  };

  // 切换下一张
  const nextSlide = () => {
    setCurrentSlide((prev) => (prev + 1) % totalSlides);
  };

  // 点击指示点
  const goToSlide = (index) => {
    setCurrentSlide(index);
  };

  return (
    <div className="carousel">
      {/* 轮播图容器 */}
      <div className="carousel-inner">
        {slides.map((slide, index) => (
          <div
            key={index}
            className={`carousel-item ${currentSlide === index ? 'active' : ''}`}
          >
            <img src={slide.image} alt={slide.title} />
            <div className="carousel-content">
              <h2>{slide.title}</h2>
              <p className="subtitle">{slide.subtitle}</p>
              <p className="description">{slide.description}</p>
            </div>
          </div>
        ))}
      </div>

      {/* 左右箭头按钮 */}
      <button className="carousel-prev" onClick={prevSlide}>❮</button>
      <button className="carousel-next" onClick={nextSlide}>❯</button>

      {/* 指示点 */}
      <div className="carousel-indicators">
        {slides.map((_, index) => (
          <span
            key={index}
            className={`indicator ${currentSlide === index ? 'active' : ''}`}
            onClick={() => goToSlide(index)}
          ></span>
        ))}
      </div>
    </div>
  );
};

export default Carousel;